<template>
  <div class="upload-imag" ref="uploadImageRef" :class="{ 'upload-margin': margin }">
    <!-- 标题 -->
    <div class="title" v-if="title">
      {{ title }}
    </div>
    <!-- 内容 -->
    <div class="upload-cont" :class="{ 'upload-card': title }">
      <div v-if="isEmpty" class="empty-block">
        <icon-empty />
        <div class="text">暂无数据</div>
      </div>
      <a-upload
        v-else
        v-model:file-list="uploadValue"
        :action="uploadAction"
        :data="appendData"
        :disabled="disabled"
        :limit="uploadLimt"
        name="files"
        image-preview
        with-credentials
        list-type="picture-card"
        ref="uploadRef"
        :auto-upload="false"
        multiple
        @change="uploadChange"
        @exceed-limit="exceedLimit"
      >
        <template #upload-button>
          <div
            class="mr-0 upload-block upload-item"
            :class="{ m_br: single == false, m_br_notitle: !title }"
            v-if="!disabled && resolveAffect"
          >
            <div class="plus">
              <icon-plus :size="14" />
            </div>
            <div class="text">上传图片</div>
            <div>支持上传{{ limitTip }}张</div>
          </div>
        </template>
        <template #upload-item="{ fileItem, index }">
          <div class="u-img-item upload-item" :class="{ m_br: single == false, m_br_notitle: !title }" :key="index">
            <a-spin
              class="upload-spin"
              :tip="`${fileItem.status == 'init' ? '压缩中 ' : '上传中 '}${parseInt(fileItem.percent * 100)}%`"
              :loading="['init', 'uploading'].includes(fileItem.status)"
            >
              <a-image :class="`image-${fileItem.uid}`" :src="fileItem.url" width="103" height="77" fit="cover">
                <template #loader>
                  <img
                    width="130px"
                    height="77px"
                    style="border: 1px solid #e5e6eb; display: block; width: 100%; height: 100%"
                    :src="imgLoading"
                  />
                </template>
              </a-image>
              <div class="action">
                <div class="btn" @click.stop="previewFn(index)"><icon-eye /><span class="text">查看</span> </div>
                <div class="btn" @click.stop="delItem(index)" v-if="!disabled"><icon-delete /><span class="text">删除</span> </div>
              </div>
            </a-spin>
          </div>
        </template>
      </a-upload>
    </div>
    <a-popover v-if="showTit" title="位置展示说明" position="bl">
      <div class="tooltip-btn" v-if="tooltip">
        <!-- <icon-info-circle-fill /> -->
        <icon-exclamation-circle />
        位置展示说明
      </div>
      <template #content>
        <!-- {{ tooltip }} -->
        举个例子，应该是一个图片
      </template>
    </a-popover>

    <a-image-preview-group v-model:visible="previewVisible" v-model:current="previewCurrent" :maskClosable="false" :srcList="previewList" />
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, watch, nextTick } from 'vue'
  import { useRoute } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import { loopImgLoadInOrder } from './scripts/img-load'
  import imgLoading from '@/assets/img-loading.png'
  import MyCompress from './scripts/upload-compress'

  const route = useRoute()

  const props = defineProps({
    title: String,
    modelValue: {
      type: [Array<string>, String],
    },
    limit: {
      type: [String, Number],
      default: 30,
    },
    disabled: Boolean,
    tooltip: String,
    single: Boolean,
    margin: Boolean,
    showTit: {
      type: Boolean,
      default: true,
    },
  })
  const emit = defineEmits(['update:modelValue', 'change'])

  const isEmpty = computed(() => {
    const modelValue = props.modelValue || []
    if (props.disabled && modelValue.length == 0) {
      return true
    }
    return false
  })

  const limitTip = computed(() => {
    if (props.single) return 1
    return props.limit
  })

  const uploadAction = import.meta.env.VITE_BASE_PATH + '/uploadFile/commonUpload'
  const appendData = { remark: route.path }
  const uploadLimt = props.single ? 1 : +props.limit
  const uploadValue = ref([])

  // 初始化 before
  const initValueWatch = watch(
    () => props.modelValue,
    (val) => {
      initValueFn(val)
    }
  )
  // 容器元素
  const uploadImageRef = ref(null)
  const initValueFn = (val) => {
    if (val) {
      const list = props.single ? [val] : val
      uploadValue.value = list.map((item, index) => {
        const openUrl = `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item}`
        return {
          uid: item,
          status: 'done',
          name: 'image.png',
          url: imgLoading,
          'data-url': openUrl,
        }
      })
      // 关闭watch
      initValueWatch && initValueWatch()
      // 图片加载器
      nextTick(() => {
        loopImgLoadInOrder(uploadImageRef.value, uploadValue.value)
      })
    }
  }
  // 首先执行一次防止v-if
  initValueFn(props.modelValue)
  // 初始化 end

  // 触发emit事件
  const emitEvent = () => {
    const uploadedList = uploadValue.value.filter((item) => item.status == 'done')
    const ids = uploadedList.map((item) => item.uid)
    let res
    // 单个图模式的不穿数组
    if (props.single) {
      res = ids[0]
    } else {
      res = ids
      if (ids.length == 0) res = undefined
    }
    emit('update:modelValue', res)
    emit('change', res)
  }

  // 删除
  const resolveAffect = ref(true)
  const delItem = (index: number) => {
    resolveAffect.value = false
    uploadValue.value.splice(index, 1)
    setTimeout(() => {
      resolveAffect.value = true
    }, 100)
    emitEvent()
  }
  // 上传图片Ref
  const uploadRef = ref()
  // 上传的文件状态发生改变时触发
  const uploadChange = (fileList: any, fileItem: any) => {
    // 文件初始化
    if (fileItem.status == 'init' && fileItem.percent == 0) {
      // 压缩图片
      MyCompress({
        fileItem: fileItem,
        success: (compressedFile: any) => {
          // 更新文件，调用 updateFile 方法
          uploadRef.value.updateFile(fileItem.uid, compressedFile)
          // 上传文件，调用 submit 方法
          uploadRef.value.submit(fileItem)
        },
      })
    } else if (fileItem.status == 'uploading') {
      if (fileItem.percent > 0.99) fileItem.percent = 0.99
    } else if (fileItem.status == 'done') {
      // 更新 uid
      uploadValue.value = fileList.map((item: any) => {
        if (item.response) {
          item.uid = item.response.result[0].fileIdStr
          console.log(`${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item.uid}`)
        }
        return item
      })
      // 判断是否全部上传完毕，不存在初始化(压缩中)及上传中的文件
      const hasUploading = uploadValue.value.some((item: any) => ['init', 'uploading'].includes(item.status))
      if (!hasUploading) {
        emitEvent()
      }

      // 关闭watch
      initValueWatch && initValueWatch()
    }
  }

  // 预览
  const previewVisible = ref(false)
  const previewCurrent = ref(0)
  const previewFn = (index) => {
    previewCurrent.value = index
    previewVisible.value = true
  }
  const previewList = computed(() => {
    return uploadValue.value.map((item) => item['data-url'] || item.url)
  })

  const exceedLimit = () => {
    Message.warning(`超过最大数量，请重新选择`)
  }
</script>

<style lang="less" scoped>
  .upload-imag {
    display: inline-block;
    background: transparent;
    &.upload-margin {
      margin-top: 20px;
      margin-right: 20px;
    }
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 20px;
      line-height: 20px;
      background: #e5e6eb;
      font-size: 12px;
      font-weight: 400;
      color: #1d2129;
    }
  }
  :deep(.arco-upload-list.arco-upload-list-type-picture-card) {
    flex-wrap: warp;
  }

  .tooltip-btn {
    margin-left: 8px;
    font-weight: 400;
    font-size: 12px;
    color: #165dff;
    line-height: 22px;
    cursor: pointer;
  }
  .upload-cont {
    &.upload-card {
      padding: 4px;
      border: 1px solid #e5e6eb;
      min-width: 114px;
      min-height: 88px;
    }
    .empty-block {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 103px;
      height: 77px;
      background: #f2f3f5;
      border-radius: 2px;
      border: 1px solid #e5e6eb;
      text-align: center;
      color: #b6b6b6;
      font-size: 32px;
      .text {
        font-size: 12px;
        font-weight: 400;
        color: #d8d8d8;
        line-height: 20px;
      }
    }
  }

  .upload-item {
    width: 103px;
    height: 77px;
    &.m_br {
      margin: 0 4px 4px 0;
    }
    &.m_br_notitle {
      margin: 0 12px 12px 0;
    }
    .upload-spin {
      /deep/ .arco-spin-mask-icon {
        width: 100%;
      }
    }
  }

  .u-img-item {
    position: relative;
    font-size: 12px;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;

    &:hover {
      .action {
        display: flex;
      }
    }
    .action {
      display: none;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
      justify-content: center;
      align-content: center;
      flex-wrap: wrap;
      border-radius: 0px 0px 2px 2px;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      :hover {
        background: rgba(0, 0, 0, 0.2);
      }
      .btn {
        width: 100%;
        height: 22px;
        text-align: center;
        .text {
          margin-left: 3px;
        }
      }
    }
  }

  .upload-block {
    text-align: center;
    padding-top: 12px;
    background: #f2f3f5;
    border: 1px solid #e5e6eb;
    border-radius: 2px;
    .text {
      margin-top: 5px;
      font-size: 12px;
      font-weight: 400;
      color: #1d2129;
      line-height: 15px;
    }
    font-size: 12px;
    font-weight: 400;
    color: #86909c;
    line-height: 20px;
  }
</style>
